package com.liangwj.springbootweb.exceptionHandle;

import com.liangwj.springbootweb.result.ErrorInfo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TODO: 创建全局异常处理类：通过使用@ControllerAdvice定义统一的异常处理类，<br/>
 *       而不是在每个Controller中逐个定义。@ExceptionHandler用来定义函数针对的异常类型，<br/>
 *       最后将Exception对象和请求URL映射到error.html中
 * @author Liangwenjun
 * @date 2018-12-12
 * @version 1.0
 */
@ControllerAdvice
public class GlobleExceptionHandler {

    public final static String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler
//    @ResponseBody
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception e) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url",request.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ErrorInfo<String> jsonErrorHandler(HttpServletRequest request, MyException myE) {
        ErrorInfo<String> errorInfo = new ErrorInfo<>();
        errorInfo.setMessage(myE.getMessage());
        errorInfo.setCode(ErrorInfo.ERROR);
        errorInfo.setUrl(String.valueOf(request.getRequestURL()));
        errorInfo.setData("error Data");
        return errorInfo;
    }
}
